﻿using System;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;

namespace Ree7.TileToolkit.Helpers
{
    public class BitmapImageFactory
    {
        public static Task<BitmapImage> Create(Uri uri)
        {
            if (Deployment.Current.Dispatcher.CheckAccess())
            {
                throw new InvalidOperationException("Waiting for the Task returned by BitmapImageFactory.Create() from the UI Thread will cause a deadlock.");
            }

            TaskCompletionSource<BitmapImage> tcs = new TaskCompletionSource<BitmapImage>();

            WebClient client = new WebClient();
            client.OpenReadCompleted += (s1, e1) =>
            {
                if (e1.Error == null)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        try
                        {
                            BitmapImage bi = new BitmapImage() { CreateOptions = BitmapCreateOptions.None };
                            bi.SetSource(e1.Result);
                            tcs.SetResult(bi);
                        }
                        catch (Exception e)
                        {
                            tcs.SetException(e);
                        }
                    });
                }
                else
                {
                    tcs.SetException(e1.Error);
                }
            };

            client.OpenReadAsync(uri);
            
            /*Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                BitmapImage bi = new BitmapImage()
                {
                    CreateOptions = BitmapCreateOptions.None
                };

                bi.ImageFailed += (s1, e1) =>
                    {
                        tcs.SetException(e1.ErrorException);
                    };
                bi.ImageOpened += (s1, e1) =>
                    {
                        tcs.SetResult(bi);
                    };
                bi.UriSource = uri;
            });*/
            
            return tcs.Task;
        }
    }
}
